package com.tanklab.signature.eth;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ChainConnection {
    // exe绝对路径
    private static final String EXE_PATH = "F:/h2chain-go.exe";

    public static String sendHashToChain(String hash) throws BlockchainException {
        Process process = null;
        String txId = null;

        try {
            // 构建执行命令
            ProcessBuilder processBuilder = new ProcessBuilder(
                    EXE_PATH,  // exe路径
                    hash       // 要上链的哈希码
            );

            // 启动进程
            process = processBuilder.start();
            int exitCode = process.waitFor();

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    // 解析交易ID
                    if (line.startsWith("txID =")) {
                        txId = line.substring(7);
                    }
                }
            }

            if (exitCode != 0) {
                StringBuilder errorMsg = new StringBuilder();
                try (BufferedReader errorReader = new BufferedReader(
                        new InputStreamReader(process.getErrorStream()))) {
                    String errorLine;
                    while ((errorLine = errorReader.readLine()) != null) {
                        errorMsg.append(errorLine).append("\n");
                    }
                }
                throw new BlockchainException("上链执行失败，错误信息：\n" + errorMsg.toString());
            }

            if (txId == null) {
                throw new BlockchainException("未找到交易ID");
            }

            return txId;

        } catch (IOException | InterruptedException e) {
            throw new BlockchainException("执行过程中出现异常: " + e.getMessage(), e);
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
    }

    // 自定义异常类
    public static class BlockchainException extends Exception {
        public BlockchainException(String message) {
            super(message);
        }

        public BlockchainException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    // 使用示例
    public static void main(String[] args) {
        ChainConnection service = new ChainConnection();
        String txId = "";
        try {
            // 假设这是生成的哈希码
            String testHash = "12321412412321";
            txId = service.sendHashToChain(testHash);
            System.out.println("交易ID: " + txId);
        } catch (BlockchainException e) {
            System.err.println("上链失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}